#include <stdio.h>
#include <math.h>

float goldSection(float (*f)(float), float a, float b, float epsilon) {
    if (a > b) {
        fprintf(stderr, "a must smaller than b\n"); 
        return 0;
    }
    if (epsilon < 0 || epsilon > 0.5) {
        fprintf(stderr, "epsilon must between 0-0.5");
        return 0;
    }
    int cnt = 0;
    float x1 = a + 0.382 * (b - a);
    float x2 = a + 0.618 * (b - a);
    float f1 = f(x1), f2 = f(x2);
    do{
        if(f1 < f2) {
            b = x2;
            f2 = f1;
            x2 = x1;
            x1 = a + 0.382 * (b - a);
            
            f1 = f(x1);
        }else{
            a = x1;
            f1 = f2;
            x1 = x2;
            x2 = a + 0.618 * (b - a);
            f2 = f(x2);
        }
        printf("a = %.3f, b = %.3f, al = %.3f, ar = %.3f, phil = %.3f, phir = %.3f, b -a = %.3f\n", a, b, x1, x2, f1, f2, fabs(b - a));
        cnt++;
    }while(b - a > epsilon);
    printf("a = %f, b = %f\n", a, b);

}

float q1function(float x){
    return exp(x) - 5 * x;
}

float q2function(float x){
    return x * x * x - 2 * x * x + 1;
}


int main(int argc, char **argv){
    goldSection(q1function, 1.0, 2.0, 0.001);
    goldSection(q2function, 0.0, 3.0, 0.001);
}
